import { ChangeEvent } from 'react'
import { useStore } from '@renderer/store/useStore'

export default function useSearch() {
  const searchText = useStore((state) => state.searchText)
  const setSearchText = useStore((state) => state.setSearchText)
  const setData = useStore((state) => state.setData)
  const webPageList = useStore((state) => state.webPageList)
  const selectPageList = useStore((state) => state.selectPageList)

  async function handleSearchChange(e: ChangeEvent<HTMLInputElement>) {
    const text = e.target.value
    setSearchText(text)
    if (text.trim() === '') {
      setData([])
      return
    }
    const list: DataType[] = await window.api.sql(
      'select * from contents where title like @searchWord or content like @searchWord',
      'findAll',
      {
        searchWord: `%${text}%`
      }
    )
    const pageList = webPageList.filter((item) => selectPageList.includes(item.id))
    const result = [...pageList, ...list]
    // @ts-ignore
    setData(result)
  }

  return {
    searchText,
    handleSearchChange
  }
}
